IF OBJECT_ID('ssf.job_get_last_run_datetime') IS NOT NULL
	DROP FUNCTION ssf.job_get_last_run_datetime
GO

CREATE FUNCTION ssf.job_get_last_run_datetime (
	@job_id UNIQUEIDENTIFIER
	, @before_run_datetime DATETIME = NULL
)
RETURNS DATETIME
AS
BEGIN
/*
<object_header>

<object_summary>
	<purpose><![CDATA[
In sysjobhistory, a record with the job start date/time is inserted with step_id = 0 when the job completes.
For the given job_id, return the maximum run datetime for the job step_id = 0,
where the job started at or before the given date/time, or if NULL, the maximum overall.
will be NULL if the job has never been run.
	]]></purpose>
</object_summary>

</object_header>
*/

	RETURN (
		SELECT MAX(ssf.job_run_datetime(run_date, run_time))
		FROM msdb.dbo.sysjobhistory WITH (NOLOCK)
		WHERE job_id = @job_id
		AND step_id = 0
		AND ssf.job_run_datetime(run_date, run_time) <= ISNULL(@before_run_datetime, ssf.job_run_datetime(run_date, run_time))
	)
END
GO
